#!/usr/bin/python
#-*- coding=utf-8 -*-

import os
import socket
import json
import struct
import time
from email.mime.text import MIMEText
from email.header	 import Header
import sys
import commands

LOG_PATH = "/data/log"

SENDER = 'david_xcy@163.com'
RECEIVER = ['xcy@ep-audio.com', 'zj@ep-audio.com']
SUBJECT_WARNING = '有监控报警邮件，请注意查收!'
SUBJECT_DAILY = '日常监控邮件，请注意查收'
SMTPSERVER = 'smtp.163.com'
MAIL_PASSWORD = 'flzx3qc'


def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
    			s.fileno(),
    			0x8915, # SIOCGIFADDR
    			struct.pack('256s', ifname[:15])
    			)[20:24])
def conn_info():
    cmd = "netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'"
    status, output = commands.getstatusoutput(cmd)
    if status != 0:
    	return None
    output = output.split('\n')
    result = dict()
    for data in output:
    	temp = data.split()
    	result[temp[0]] = temp[1]
    return result

def send_mail(title, send_str):
    msg = MIMEText(send_str, 'plain', 'utf-8')
    msg['Subject'] = Header(title, 'utf-8')
    msg['From'] = 'minik_monitor<david_xcy@163.com>'
    msg['To'] = ';'.join(RECEIVER)
    try:
    	smtp = smtplib.SMTP()
    	smtp.connect(SMTPSERVER)
    	smtp.login(SENDER, MAIL_PASSWORD)
    	smtp.sendmail(SENDER, RECEIVER, msg.as_string())
    except Exception, e:
    	print "send mail to %s error!" % ";".join(RECEIVER)
    	print e
    smtp.quit()

def main():
    log_path = os.path.join(LOG_PATH, "%s/*/world_oss*" %time.strftime("%Y%m%d", time.localtime(time.time() - 86400)))
    print log_path , LOG_PATH
    cmd = '''grep "PlayerLogin" %s | awk -F "|" '!a[$7]++{print $7}' | wc -l''' %log_path
    login_count = -1
    status, output= commands.getstatusoutput(cmd)
    print output, "---1-----------"
    if status != 0:
        login_count = -1

    cmd = '''grep -i "register" %s | awk -F "|" '!a[$7]++{print $7}' | wc -l''' %log_path 
    register_count = -1
    status, output= commands.getstatusoutput(cmd)
    print output, "--------------2"
    if status != 0:
        register_count = -1
    print login_count, register_count, "--------------3"
    stay_count = float(login_count) - float(register_count)
    print login_count, register_count, stay_count, 'asdf'
    

if __name__ == "__main__":
    main()
